﻿using Mapster;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;

namespace Luka;

/// <summary>
/// SqlSugar操作类
/// </summary>
[NotScanned]
public static class SqlSugarSetup
{
    /// <summary>
    /// sqlsugar服务注册
    /// </summary>
    public static IServiceCollection AddSqlsugar(this IServiceCollection services)
    {
        //默认启用的取配置项
        var connectionConfigs = InternalApp.GetSection<List<SqlsugarConfig>>("ConnectionStrs")?.Where(it => it.IsEnable).ToList();

        var sqlSugarScope = new SqlSugarScope(connectionConfigs?.Adapt<List<ConnectionConfig>>(),
            db =>
            {
                SetFilter(db);
                connectionConfigs?.ForEach(config =>
                {
                    SetConfig(config);
                    var dbProvider = db.GetConnectionScope(config.ConfigId);
                    AddAop(dbProvider);
                });
            });
        return services.AddSingleton<ISqlSugarClient>(sqlSugarScope);
    }

    /// <summary>
    /// sqlsugar_config
    /// </summary>
    private static void SetConfig(SqlsugarConfig config)
    {
        config.MoreSettings = new ConnMoreSettings
        {
            IsAutoRemoveDataCache = true
        };
    }

    /// <summary>
    /// Aop方法
    /// </summary>
    private static void AddAop(SqlSugarScopeProvider provider)
    {
        //执行前
        provider.Aop.OnLogExecuting = (sql, pars) =>
        {
            SqlSugarAop.LogSql(Enum.GetName(typeof(SugarActionType), provider.SugarActionType) ?? "Query", sql, pars);
        };
        //错误
        provider.Aop.OnError = err =>
        {
            SqlSugarAop.LogSql(Enum.GetName(typeof(SugarActionType), provider.SugarActionType) ?? "Query", err.Sql, (SugarParameter[])err.Parametres);
        };
    }

    /// <summary>
    /// 过滤器
    /// </summary>
    private static void SetFilter(SqlSugarClient db)
    {
        db.QueryFilter.AddTableFilter<IDeleted>(it => it.IsDeleted == false);
    }
}